<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-row v-if="form.lastHistoricalId" :span="24">
          <div style="float: right;">
            <el-button size="mini" type="primary" style=" margin-right: 50px;" @click="contractComparisonBtn">
              {{ $t('合同比对') }}
            </el-button>
          </div>
        </el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applyUserId">
            <UserSelect v-model="form.applyUserId" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <DatePicker v-model="form.applyTime" :placeholder="$t('申请时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同名称')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('合同名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="type">
            <span slot="label">
              {{ $t('合同类型') }}
              <el-tooltip :content="$t('类型为“投资协议”并且为“付款”时,审批完成后将会把当前合同中的签约主体同步至项目主体中')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-select v-model="form.type" :placeholder="$t('合同类型')" @change="typeOnChange">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('收付款类型')" prop="isPayment">
            <el-radio-group v-model="form.isPayment">
              <el-radio
                v-for="dict in isPaymentOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
                @change="paymentOnChange"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否用印')" prop="isSeal">
            <el-radio-group v-model="form.isSeal" @change="sealOnChange">
              <el-radio
                v-for="dict in isSealOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <template v-if="typeShow">
          <el-col :span="12">
            <el-form-item :label="$t('合同金额') + $t('金额单位')" prop="money">
              <Money v-model="form.money" :placeholder="$t('合同金额')" unit="w" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('年化利率(%)')" prop="interestRate">
              <Money v-model="form.interestRate" :placeholder="$t('年化利率(%)')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('起息日')" prop="valueDate">
              <DatePicker v-model="form.valueDate" :placeholder="$t('起息日')" />
            </el-form-item>
          </el-col>
          <el-col v-if="isShowDeal === 'hidden'" :span="12">
            <el-form-item :label="$t('关联项目')" prop="dealId">
              <MainBodySelect
                v-model="form.dealId"
                :show-label="false"
                :parameters="'deal'"
              />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <el-form-item :label="$t('合同摘要')" prop="abstracts">
            <el-input v-model="form.abstracts" type="textarea" :placeholder="$t('合同摘要')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.isPayment === 'payment'" :span="24">
          <el-form-item :label="$t('付款先决条件')" prop="paymentPrerequisites">
            <el-input v-model="form.paymentPrerequisites" type="textarea" maxlength="2000" :placeholder="$t('付款先决条件')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('特殊条款')" prop="specialTerms">
            <el-input v-model="form.specialTerms" type="textarea" maxlength="2000" :placeholder="$t('特殊条款')" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 用印明细 -->
      <div v-if="form.isSeal === 'Y'" style="margin-top:8px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('用印明细') }}</span>
        </div>
        <el-table :data="form.oaSeal.oaSealDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSeal.oaSealDetailList.' + scope.$index + '.investMainType'" :rules="oaSealDetailListRules.investMainType">
                <dictSelect
                  v-model="scope.row.investMainType"
                  :clearable="true"
                  dictionary="main_body_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSeal.oaSealDetailList.' + scope.$index + '.investMain'" :rules="oaSealDetailListRules.investMain">
                <MainBodySelect
                  v-model="scope.row.investMain"
                  :parameters="scope.row.investMainType"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSeal.oaSealDetailList.' + scope.$index + '.sealType'" :rules="oaSealDetailListRules.sealType">
                <el-select
                  v-model="scope.row.sealType"
                  multiple
                  :placeholder="$t('用印类型')"
                >
                  <el-option
                    v-for="dict in sealTypeOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'oaSeal.oaSealDetailList.' + scope.$index + '.remark'" :rules="oaSealDetailListRules.remark">
                <el-input v-model="scope.row.remark" type="textarea" :placeholder="$t('备注')" maxlength="2000" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:contract:remove']" type="text" icon="el-icon-delete" @click="delSeal(scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addSeal">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <!--签约主体-->
      <div style="margin-top:15px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('签约主体') }}</span>
        </div>
        <el-table :data="form.dealContractInvestDebts" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('主体类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractInvestDebts.' + scope.$index + '.investType'" :rules="dealContractInvestDebtsRules.investType">
                <dictSelect
                  v-model="scope.row.investType"
                  :clearable="true"
                  dictionary="deal_investment_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('主体名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('主体名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractInvestDebts.' + scope.$index + '.investMain'" :rules="dealContractInvestDebtsRules.investMain">
                <MainBodySelect
                  v-model="scope.row.investMain"
                  :parameters="scope.row.investType"
                  @change="investOnChange($event, scope.$index)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <!--
          <el-table-column :label="$t('SPV')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('SPV') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractInvestDebts.' + scope.$index + '.spvId'" :rules="dealContractInvestDebtsRules.spvId">
                <spv-select v-model="scope.row.spvId" />
              </el-form-item>
            </template>
          </el-table-column>
          -->
          <el-table-column v-if="form.type === 'TZXY'" :label="$t('投资金额') + $t('金额单位')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('投资金额') + $t('金额单位') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractInvestDebts.' + scope.$index + '.investmentAmount'" :rules="dealContractInvestDebtsRules.investmentAmount">
                <Money v-model="scope.row.investmentAmount" unit="w" :placeholder="$t('投资金额')" @change="investmentAmountCompute" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('备注') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractInvestDebts.' + scope.$index + '.remark'">
                <el-input v-model="scope.row.remark" type="textarea" maxlength="2000" :placeholder="$t('备注')" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delInvest(scope.row, scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addInvest">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <!-- 收付款计划 -->
      <div v-if="form.isPayment !== 'no'" style="margin-top: 15px;">
        <div class="area-header">
          <span class="area-header-title">{{ form.isPayment === 'collection' ? $t('收款计划') : $t('付款计划') }}</span>
        </div>
        <el-table :data="form.dealContractPlanDebts" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('主体名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('主体名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractPlanDebts.' + scope.$index + '.investId'" :rules="dealContractPlanDebtsRules.investId">
                <el-select v-model="scope.row.investId" clearable size="small">
                  <el-option
                    v-for="(item, index) in investOptions"
                    :key="index"
                    :label="item.investorName"
                    :value="item.investorId"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <template>
            <el-table-column v-if="form.isPayment === 'payment'" :key="1" :label="$t('预计付款时间')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计付款时间') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanDebts.' + scope.$index + '.paymentTime'" :rules="dealContractPlanDebtsRules.paymentTime">
                  <DatePicker v-model="scope.row.paymentTime" :placeholder="$t('预计付款时间')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="form.isPayment === 'payment'" :key="2" :label="$t('预计付款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计付款金额') }} {{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanDebts.' + scope.$index + '.paymentMoney'" :rules="dealContractPlanDebtsRules.paymentMoney">
                  <Money v-model="scope.row.paymentMoney" unit="w" />
                </el-form-item>
              </template>
            </el-table-column>
          </template>
          <template>
            <el-table-column v-if="form.isPayment === 'collection'" :key="3" :label="$t('预计收款时间')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计收款时间') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanDebts.' + scope.$index + '.collectionTime'" :rules="dealContractPlanDebtsRules.collectionTime">
                  <DatePicker v-model="scope.row.collectionTime" :placeholder="$t('预计收款时间')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="form.isPayment === 'collection'" :key="4" :label="$t('预计收款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计收款金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'dealContractPlanDebts.' + scope.$index + '.collectionMoney'" :rules="dealContractPlanDebtsRules.collectionMoney">
                  <Money v-model="scope.row.collectionMoney" unit="w" />
                </el-form-item>
              </template>
            </el-table-column>
          </template>
          <el-table-column :label="$t('币种')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('币种') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractPlanDebts.' + scope.$index + '.currency'" :rules="dealContractPlanDebtsRules.currency">
                <dictSelect
                  v-model="scope.row.currency"
                  :clearable="true"
                  dictionary="currency"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('备注') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealContractPlanDebts.' + scope.$index + '.remark'">
                <el-input v-model="scope.row.remark" type="textarea" maxlength="2000" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delPaymentPlan(scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentPlan">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <!--合同关键条款-->
      <div style="margin-top:15px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('合同关键条款') }}</span>
        </div>
        <el-table :data="form.dealTermsDebts" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款类型')" align="center" width="300">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTermsDebts.' + scope.$index + '.type'" :rules="dealTermsDebtsRules.type">
                <dictSelect
                  v-model="scope.row.type"
                  :clearable="true"
                  dictionary="key_terms_tyoe"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款内容')" align="center" min-width="200">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款内容') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTermsDebts.' + scope.$index + '.remark'" :rules="dealTermsDebtsRules.remark">
                <el-input
                  v-model="scope.row.remark"
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 8}"
                  maxlength="2000"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('定时提醒')" align="center" min-width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="remindHandle(scope.$index)">定时提醒</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:contract:remove']" type="text" icon="el-icon-delete" @click="delTerms(scope.row, scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addTerms">{{ $t("添加") }}</el-button>
        </div>
      </div>

      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" data-type="deal_contract_debt" :business-id="dealId" :btn-show="!otherBtnHide" />

      <!-- 合同比对页面 -->
      <el-dialog :title="$t('合同比对')" :visible.sync="dealContractProcessOpen" width="99%" top="1%" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
        <dealContractDebtProcess ref="dealContractDebtProcess" />
      </el-dialog>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="!changeContractBtnStatus" ref="formBtn" :bus-data="form" has-permi="debt:contract" :btn-hide="btnHide" :menu-key="menuKey" />
      <div v-else>
        <el-button @click="cancel()">{{ $t("取消") }}</el-button>
        <el-button
          v-hasPermi="['deal:contract:edit']"
          type="primary"
          @click="submitForm('changeContract')"
        >{{ $t("变更并启动流程") }}</el-button>
      </div>
    </div>

    <!-- 定时提醒 -->
    <el-dialog :title="$t('定时提醒')" :visible.sync="remindOpen" width="40%" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <el-form
        v-if="form.dealTermsDebts[termsIndex]"
        ref="remindForm"
        :model="form.dealTermsDebts[termsIndex]"
        :rules="remindRules"
        label-width="120px"
        label-position="top"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
              <el-radio-group v-model="form.dealTermsDebts[termsIndex].reminderFrequency">
                <el-radio
                  v-for="dict in reminderFrequencyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.dealTermsDebts[termsIndex].reminderFrequency === 'TIMER'" :span="12">
            <el-form-item :label="$t('定时提醒时间')" prop="remindTime">
              <el-date-picker
                v-model="form.dealTermsDebts[termsIndex].remindTime"
                clearable
                style="width: 200px"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm"
                :placeholder="$t('定时提醒时间')"
              />
            </el-form-item>
          </el-col>
          <el-col v-else :span="24">
            <el-form-item :label="$t('频率提醒表达式')" prop="cron">
              <Cron v-model="form.dealTermsDebts[termsIndex].cron" :cron-value.sync="form.dealTermsDebts[termsIndex].frequencyCronValue" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒状态')" prop="status">
              <el-switch
                v-model="form.dealTermsDebts[termsIndex].status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-text="$t('开启')"
                :inactive-text="$t('关闭')"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒人')" prop="remindUserId">
              <UserSelect
                v-model="form.dealTermsDebts[termsIndex].remindUserId"
                :multiple="true"
                :placeholder="$t('提醒人')"
                :popper-append-to-body="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="remindConfirmHandle">{{ $t('确 定') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
    import MainBodySelect from '@/components/MainBodySelect/index'
    import { saveDealContractDebt, getDealContractDebt, delDealContractDebtByTerms, changeDealContractDebt } from '@/api/deal/contract/debt/dealContractDebt'
    import { findByDealId } from '@/api/deal/investment/dealInvestment'
    import { getDealName } from '@/api/base/deal/dealBase'
    import { getAllInvestor } from '@/api/fund/fundBase'
    import dealContractDebtProcess from '@/views/deal/contract/debt/dealContractDebtProcess.vue'
    import Cron from '@/components/Cron'
    export default {
      components: {
        MainBodySelect,
        dealContractDebtProcess,
        Cron
      },
      data() {
        // 校验合同金额 不能为0 和负数
        const checkMoney = (rule, value, callback) => {
          if (value === undefined || value === '' || value === 0 || value === '0' || value === null) {
            callback(new Error(this.$t('必填信息')))
          } else {
            callback()
          }
        }
        return {
          // 菜单标识
          menuKey: 'deal_contract_debt',
          // 合同类型字典
          typeOptions: [],
          // 收付款类型字典
          isPaymentOptions: [],
          // 是否用印字典
          isSealOptions: [],
          // 用印类型
          sealTypeOptions: [],
          otherBtnHide: false,
          // 是否隐藏保存按钮
          btnHide: false,
          // 项目ID
          dealId: this.$route.query.id,
          // 表单参数
          form: {},
          // 定时提醒
          remindOpen: false,
          // 点击定时提醒关键条款索引
          termsIndex: undefined,
          reminderFrequencyOptions: [],
          // 表单校验
          rules: {
            applyUserId: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], applyTime: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], name: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], type: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], isPayment: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], isSeal: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ], money: [
              { required: true, validator: checkMoney, trigger: ['blur', 'change'] }
            ], actTitle: [
              { required: true, message: this.$t('必填信息'), trigger: 'blur' }
            ]
          },
          // 费用明细
          oaSealDetailListRules: {
              investMainType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
              investMain: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
              sealType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
            },
          remindRules: {
            timerReminderTime: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
            cron: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
            reminderFrequency: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
            remindTime: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
            remindUserId: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
          },
          // 签约主体
          dealContractInvestDebtsRules: {
              investType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
              investMain: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
              investmentAmount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
            },
          // 收付款计划
          dealContractPlanDebtsRules: {
            investId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
            paymentTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            paymentMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
            collectionTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
            collectionMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
          },
          // 关键条款
          dealTermsDebtsRules: {
            name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
            type: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
            remark: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
          },
          // 遮罩层
          loading: false,
          // 操作按钮默认不展示
          buttonShow: true,
          // 根据选择的合同类型判断是否展示合同金额、年化利率、起息日
          typeShow: false,
          // 当前项目投资主体
          investmentOptions: [],
          // 签约主体所选择的主体名称 给 收付款计划使用
          investOptions: [],
          isShowDeal: undefined,
          // 全部基金
          fundOptions: [],
          monitorQueryParams: {
            dealId: this.$route.query.id,
            money: 0
          },
          // 合同变更 . 备份修改前的所有数据
          oldDealContractDebt: undefined,
          dealContractProcessOpen: false,
          // 合同变更重启流程按钮
          changeContractBtnStatus: false
        }
      },
      watch: {
        'form.money': {
          handler(val) {
            if (val !== '' && val !== undefined && val !== 0) {
              this.monitorQueryParams.money = val
            }
          }
        }
      },
      mounted() {
        this.$bus.$emit('async_done')
      },
      created() {
        this.getDicts('deal_contract_type_select').then(response => {
            this.typeOptions = response.data
        })
        this.getDicts('payment_no_deal').then(response => {
            this.isPaymentOptions = response.data
        })
        this.getDicts('reminder_frequency').then(response => {
          this.reminderFrequencyOptions = response.data
        })
        this.getDicts('sys_yes_no').then(response => {
            this.isSealOptions = response.data
        })
        this.getDicts('seal_type').then(response => {
          this.sealTypeOptions = response.data
        })
        getAllInvestor().then(response => {
          this.fundOptions = response.data
        })
      },
      methods: {
            // 初始化数据
            init(data) {
              this.changeContractBtnStatus = false
              this.initForm(data, () => {})
            },
            initForm(data, callback) {
              this.loading = true
              this.investOptions = []
              this.dealId = this.$route.query.id ? this.$route.query.id : data.dealId
              if (this.dealId === undefined || this.dealId === null || this.dealId === '') {
                this.isShowDeal = 'hidden'
              }
                if (data != null && data.id !== undefined) {
                    getDealContractDebt(data.id).then(response => {
                      this.form = Object.assign({}, response.data)
                      this.typeOnChange(this.form.type)
                      this.$set(this.form, 'dealContractInvestDebts', response.data.dealContractInvestDebts)
                      this.form.isPayment = response.data.isPayment
                      this.form.isSeal = response.data.isSeal
                      this.$forceUpdate()
                      // 初始化收付款计划主体名称
                      this.investOptions = this.form.dealContractInvestDebts.map((item) => {
                        return {
                          investorId: item.investMain,
                          investorName: item.investMainName
                        }
                      })
                      this.loading = false
                      // 备份数据
                      this.oldDealContractDebt = JSON.parse(JSON.stringify(this.form))
                      this.loading = false
                      callback()
                    })
                } else {
                    this.reset()
                    if (data !== null) {
                      // 默认带出流程中必须要传的附件
                      this.form.fileList = data.fileList
                    }
                    // 获取当前项目的投资主体
                    findByDealId(this.dealId).then(response => {
                      this.investmentOptions = response.data
                      if (this.investmentOptions && this.investmentOptions.length > 0) {
                        // 初始化签约主体
                        this.investmentOptions.forEach((item) => {
                          this.addInvest(item)
                          const invest = {
                            investorId: item.investorId,
                            investorName: item.investorName,
                            spvId: item.spvId
                          }
                          this.investOptions.push(invest)
                          console.log(this.investOptions)
                          this.loading = false
                        })
                      } else {
                        this.loading = false
                      }
                    })
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                applyUserId: this.$store.state.user.userId,
                sourceId: undefined,
                dealId: this.dealId,
                applyTime: new Date(),
                name: undefined,
                type: undefined,
                isPayment: 'no',
                isSeal: 'N',
                company: undefined,
                money: undefined,
                payCompletionTime: undefined,
                abstracts: undefined,
                actId: undefined,
                actStatus: undefined,
                paymentPrerequisites: undefined,
                specialTerms: undefined,
                interestRate: undefined,
                valueDate: undefined,
                remark: undefined,
                createBy: undefined,
                updateBy: undefined,
                createTime: undefined,
                updateTime: undefined,
                delFlag: undefined,
                actTitle: undefined,
                oaSeal: {
                  oaSealDetailList: []
                }, // 用印明细
                dealContractInvestDebts: [], // 签约主体
                dealContractPlanDebts: [], // 收付款计划
                dealTermsDebts: [], // 关键条款
                fileList: [] // 文件上传
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm(type) {
                // 关闭form页面遮罩层
                this.loading = false
                if (type !== 'actSave') {
                  // 关闭form页面
                  this.$parent.$parent.formOpen = false
                  // 刷新list页面
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm(type) {
              console.log(type)
              return new Promise((resolve, reject) => {
                if ((this.form.isPayment === 'payment' || this.form.isPayment === 'collection')) {
                  var flag = false
                  var paymentList = []
                  var collectionList = []
                  if (this.form.isPayment === 'payment') {
                    paymentList = this.form.dealContractPlanDebts
                  }
                  if (this.form.isPayment === 'collection') {
                    collectionList = this.form.dealContractPlanDebts
                  }
                  if (paymentList !== undefined && paymentList !== null && paymentList !== '' && paymentList.length > 0) {
                    var tempPaymentList = 0
                    paymentList.forEach(item => {
                      tempPaymentList += item.paymentMoney
                    })
                    flag = parseFloat(tempPaymentList) === parseFloat(this.form.money)
                  }
                  if (collectionList !== undefined && collectionList !== null && collectionList !== '' && collectionList.length > 0) {
                    var tempCollectionMoney = 0
                    collectionList.forEach(item => {
                      tempCollectionMoney += item.collectionMoney
                    })
                    flag = parseFloat(tempCollectionMoney) === parseFloat(this.form.money)
                  }
                  if (!flag) {
                    this.$confirm(this.$t('收付款计划金额与合同金额不一致,是否继续?'), this.$t('警告'), {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(() => {
                      this.submitFormStart(type).then((dataId) => {
                        resolve(dataId)
                      })
                    }).catch(() => {
                      reject()
                    })
                  } else {
                    this.submitFormStart(type).then((dataId) => {
                      resolve(dataId)
                    })
                  }
                } else {
                  this.submitFormStart(type).then((dataId) => {
                    resolve(dataId)
                  })
                }
              })
            },
            submitFormStart: function(type) {
              this.$refs['form'].validate()
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  // 验证数据
                  if (valid) {
                    if (type === 'changeContract') {
                      this.startProcess({ id: this.form.id, type: 'changeContract' })
                      resolve()
                    } else {
                      // 弹出遮罩层
                      this.loading = true
                      // 保存方式，如果值为actSave则是从流程表单中进行的保存，默认将delFlag 设置为2,审批通过后在更新为0
                      this.form.saveType = type
                      // 保存数据
                      saveDealContractDebt(this.form).then(response => {
                        if (response.code === 200) {
                          this.form = response.data
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 启动流程
                            this.startProcess(response.data)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm(type)
                          }
                          resolve(response.data.id)
                        } else {
                          this.msgError(response.msg)
                          this.loading = false
                          reject(response)
                        }
                      })
                    }
                  } else {
                    this.locationError(document)
                  }
                })
              })
           },
            // 启动流程
           startProcess: async function(data) {
               this.loading = false
               var dealName = await getDealName(this.dealId)
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '「' + dealName + '」' + ':' + this.form.actTitle
               // 业务表名
               processData.dataTable = 'deal_contract_debt'
               // 业务ID
               processData.dataId = data.id
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/deal/contract/debt/dealContractDebtForm'
               processData.viewPath = '@/views/deal/contract/debt/dealContractDebtView'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey

               // 是否点击保存按钮后,启动流程前执行方法
               if (data.type === 'changeContract') {
                 processData.onBeforeProcess = true
                 this.form.oldDealContractDebt = this.oldDealContractDebt
                 processData.form = this.form
               }
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          typeOnChange(val) {
              if (val === 'TZXY' || val === 'BCXY') {
                this.typeShow = true
                this.form.isPayment = 'payment'
              } else {
                this.form.isPayment = 'no'
                this.typeShow = false
                this.form.money = undefined
                this.form.interestRate = undefined
                this.form.valueDate = undefined
              }
              this.form.money = undefined
              if (this.typeShow) {
                this.investmentAmountCompute()
              }
          },
          // 添加用印主体
          addSeal(data) {
            var row = {
              id: undefined,
              investMainType: '',
              investMain: '',
              sealType: '',
              remark: ''
            }
            if (data) {
              row = {
                id: undefined,
                investMainType: data.investorType,
                investMain: data.investorId,
                sealType: '',
                remark: ''
              }
            }
            if (!(this.form.oaSeal.oaSealDetailList instanceof Array)) {
              this.$set(this.form.oaSeal, 'oaSealDetailList', [])
            }
            this.$nextTick(() => {
              this.form.oaSeal.oaSealDetailList.push(row)
            })
          },
          delSeal(index) {
            this.form.oaSeal.oaSealDetailList.splice(index, 1)
          },
          sealOnChange(val) {
            if (!this.form.oaSeal.oaSealDetailListTemp) {
              this.form.oaSeal.oaSealDetailListTemp = this.form.oaSeal.oaSealDetailList
            }
            this.form.oaSeal.oaSealDetailList = []
            if (val === 'Y') {
              this.form.oaSeal.oaSealDetailList = this.form.oaSeal.oaSealDetailListTemp
            }
          },
          // 添加签约主体
          addInvest(data) {
            var row = {
              id: undefined,
              investType: '',
              investMain: '',
              remark: ''
            }
            if (data) {
              row = {
                id: undefined,
                investType: data.investorType,
                investMain: data.investorId,
                spvId: data.spvId,
                remark: ''
              }
            }
            // 同时初始化用印明细
            if (!(this.form.dealContractInvestDebts instanceof Array)) {
              this.$set(this.form, 'dealContractInvestDebts', [])
            }
            this.$nextTick(() => {
              this.form.dealContractInvestDebts.push(row)
            })
          },
          // 删除签约主体
          delInvest(row, index) {
            this.form.dealContractInvestDebts.splice(index, 1)
            this.delPlanSelect(row.investMain)
            this.investmentAmountCompute()
          },
          paymentOnChange() {
            this.form.dealContractPlanDebts = []
          },
          // 添加收付款计划
          addPaymentPlan() {
            const row = {
              id: undefined,
              investId: undefined,
              paymentTime: undefined,
              currency: 'CNY',
              paymentMoney: undefined,
              collectionTime: undefined,
              collectionMoney: undefined
            }
            if (!(this.form.dealContractPlanDebts instanceof Array)) {
              this.$set(this.form, 'dealContractPlanDebts', [])
            }
            this.$nextTick(() => {
              this.form.dealContractPlanDebts.push(row)
            })
          },
          // 签约主体去重 不可以选择重复主体
          investOnChange(val, index) {
            var count = 0
            this.form.dealContractInvestDebts.forEach((item) => {
              if (val === item.investMain) {
                ++count
              }
              if (count > 1) {
                this.msgError(this.$t('签约主体存在重复!'))
                this.form.dealContractInvestDebts.splice(index, 1)
              }
            })
            if (count === 1) {
              // 签约主体选择完主体后同步付款计划主体选择
              this.investOptions = []
              var investIds = []
              if (this.form.dealContractInvestDebts) {
                this.form.dealContractInvestDebts.forEach(item => {
                  if (item.investMain !== '' && item.investMain !== null && item.investMain !== undefined) {
                    var temp = this.fundOptions.find(item2 => item2.id === item.investMain)
                    const invest = {
                      investorId: temp.id,
                      investorName: temp.name
                    }
                    investIds.push(item.investMain)
                    this.investOptions.push(invest)
                  }
                })
              }
              // 校验付款计划. 目的是为了出现id
              if (this.form.dealContractPlanDebts) {
                this.form.dealContractPlanDebts.forEach((item, index) => {
                  if (!investIds.includes(item.investId)) {
                    this.form.dealContractPlanDebts.splice(index, 1)
                  }
                })
              }
            }
            // 剔除主体中不存在的 名称
            console.log('剔除主体中不存在的 名称')
            try {
              const tempInvestArr = []
              if (this.form.dealContractInvestDebts !== undefined && this.form.dealContractInvestDebts !== null) {
                // 获取主体中所有的id
                this.form.dealContractInvestDebts.forEach(item => {
                  tempInvestArr.push(item.investMain)
                })
                // 遍历收付款计划, 看看收付款计划中是否存在 主体中的主体名称
                var tempPlanId = []
                this.investOptions.forEach((item, index) => {
                  // 不存在删掉 收付款主体的option, tempInvestArr收集的是被删掉的option 如果收付款计划中存在这些id说明这些id是一乱码的
                  if (!tempInvestArr.includes(item.investorId)) {
                    tempPlanId.push(item.investorId)
                    this.investOptions.splice(index, 1)
                  }
                })
                // 删除后 会显示一串id 将id 置空
                this.form.dealContractPlanDebts.some((item2, index2) => {
                  if (tempPlanId.includes(item2.investId)) {
                    this.form.dealContractPlanDebts[index2].investId = undefined
                  }
                })
              }
            } catch (e) {
              console.log(e)
            }
          },
          // 投资协议 + 付款时 计算投资金额总和填写到项目合同
          investmentAmountCompute() {
            if (this.form.dealContractInvestDebts) {
              var sumMoney = 0.0
              this.form.dealContractInvestDebts.forEach(item => {
                var money = parseFloat(item.investmentAmount)
                if (money === undefined || isNaN(money)) {
                  money = 0.0
                }
                sumMoney += money
              })
              if (sumMoney === 0.0 || sumMoney === 0) {
                this.form.money = undefined
              } else {
                this.form.money = sumMoney
              }
            }
          },
          // 删除收付款计划主体名称下拉值
          delPlanSelect(val) {
            if (val !== '' && val !== undefined && val !== null) {
              var investIndex = this.investOptions.findIndex((item) => {
                console.log(item.investorId === val)
                return item.investorId === val
              })
              this.investOptions.splice(investIndex, 1)
              for (let i = 0; i < this.form.dealContractPlanDebts.length; i++) {
                if (this.form.dealContractPlanDebts[i].investId === val) {
                  this.form.dealContractPlanDebts.splice(i, 1)
                }
              }
            }
          },
          // 删除收付款计划
          delPaymentPlan(index) {
            this.form.dealContractPlanDebts.splice(index, 1)
          },
          // 添加合同关键条款
          addTerms() {
            const row = {
              id: undefined,
              investType: '',
              investMain: '',
              paymentTime: '',
              paymentMoney: 0,
              collectionTime: '',
              collectionMoney: '',
              currency: '',
              stake: '',
              remark: '',
              status: 1,
              reminderFrequency: 'TIMER',
              cron: '',
              frequencyCronValue: undefined
            }
            if (!(this.form.dealTermsDebts instanceof Array)) {
              this.$set(this.form, 'dealTermsDebts', [])
            }
            this.$nextTick(() => {
              this.form.dealTermsDebts.push(row)
            })
          },
          remindHandle(index) {
            this.termsIndex = index
            this.remindOpen = true
          },
          // 删除关键条款
          delTerms(row, index) {
            var that = this
            const id = row.id
            console.log('删除条款')
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
              .then(function() {
                 delDealContractDebtByTerms(id).then(() => {
                  that.form.dealTermsDebts.splice(index, 1)
                  that.msgSuccess(that.$t('删除成功'))
                })
              }).catch(function() {})
            } else {
              this.form.dealTermsDebts.splice(index, 1)
            }
          },
          // 合同变更
          async contractChanges(data) {
            console.log('初始化合同变更数据')
            this.loading = true
            // 显示变更按钮
            this.changeContractBtnStatus = true
            this.initForm(data, () => {
              // 显示添加按钮
              // this.form.actStatus = undefined
            })
          },
          // 合同比对按钮
          contractComparisonBtn() {
            this.dealContractProcessOpen = true
            this.title = '合同比对'
            this.$nextTick(() => {
              this.$refs.dealContractDebtProcess.newData = { id: this.form.id, dealId: this.form.dealId }
              this.$refs.dealContractDebtProcess.oldData = { id: this.form.lastHistoricalId, dealId: this.form.dealId }
              this.$refs.dealContractDebtProcess.init()
            })
          },
          // 保存合同变更数据
          onExtraProcessStart(data) {
            return new Promise((resolve, reject) => {
              var form = data.processData.form
              const getCircularReplacer = () => {
                const seen = new WeakSet()
                return (key, value) => {
                  if (typeof value === 'object' && value !== null) {
                    if (seen.has(value)) {
                      return
                    }
                    seen.add(value)
                  }
                  return value
                }
              }
              var forms = JSON.parse(JSON.stringify(form, getCircularReplacer()))
              changeDealContractDebt(forms).then(response => {
                if (response.code === 200 && response.msg !== '变更时发生异常!') {
                  resolve()
                } else {
                  reject()
                }
              })
            })
          },
        remindConfirmHandle() {
          this.$refs['remindForm'].validate(valid => {
            if (valid) {
              this.remindOpen = false
            }
          })
        }
      }
    }
</script>
